package com.comtop.topcloud.device.controller;

import com.comtop.topcloud.device.model.CommandRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.comtop.topcloud.device.service.EventTableService;
import com.comtop.topcloud.device.model.mysql.EventTable;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 召读事件表 前端控制器
 * </p>
 *
 * @author 张俊彬
 * @since 2025-01-04
 */
@Controller
@RequestMapping("/event-table")
public class EventTableController {


    @Autowired
    private EventTableService eventTableService;

    @PostMapping("/send-command")
    public ResponseEntity<Object> sendCommand(@RequestBody CommandRequest params) {
        Long eventId = eventTableService.sendCommand(params); // 调用服务层的sendCommand方法

        // 创建一个 HashMap 来构造返回的响应数据
        Map<String, Object> response = new HashMap<>();

        if (eventId != null) {
            // 命令发送成功，返回 eventId
            response.put("message", "send command successfully");
            response.put("eventId", eventId);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            // 命令发送失败，返回错误信息
            response.put("message", "send command failed");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @GetMapping(value = "/")
    public ResponseEntity<Page<EventTable>> list(@RequestParam(required = false) Integer current, @RequestParam(required = false) Integer pageSize) {
        if (current == null) {
            current = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Page<EventTable> aPage = eventTableService.page(new Page<>(current, pageSize));
        return new ResponseEntity<>(aPage, HttpStatus.OK);
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<EventTable> getById(@PathVariable("id") String id) {
        return new ResponseEntity<>(eventTableService.getById(id), HttpStatus.OK);
    }

    @PostMapping(value = "/create")
    public ResponseEntity<Object> create(@RequestBody EventTable params) {
        eventTableService.save(params);
        return new ResponseEntity<>("created successfully", HttpStatus.OK);
    }

    @PostMapping(value = "/delete/{id}")
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        eventTableService.removeById(id);
        return new ResponseEntity<>("deleted successfully", HttpStatus.OK);
    }

    @PostMapping(value = "/update")
    public ResponseEntity<Object> update(@RequestBody EventTable params) {
        eventTableService.updateById(params);
        return new ResponseEntity<>("updated successfully", HttpStatus.OK);
    }
}
